package net.howson.phil.datahiding.stream;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;

public class ComponentRecoveryStream extends InputStream {

	private final int actualWidth;
	private final int height;
	private final int[] components = new int[3];
	private final BufferedImage inputImage;
	private int loops;
	private int width;
	private int x;
	private int y;
	private int offsetX;

	private int cursor = 3;
	private boolean ended;

	public ComponentRecoveryStream(BufferedImage inputImage, int loops) {
		this.inputImage = inputImage;
		this.loops = loops;
		width = inputImage.getWidth();
		height = inputImage.getHeight();
		actualWidth = width;
	}

	public void setRepititions(int reps) {
		width = actualWidth / reps;
	}

	@Override
	public int read() throws IOException {
		if (!ended) {
			if (cursor == components.length) {
				cursor = 0;
				int rgb = inputImage.getRGB(x + offsetX, y);
				int red = (rgb & 0x00ff0000) >>> 16;
				int green = (rgb & 0x0000ff00) >>> 8;
				int blue = rgb & 0x000000ff;
				components[0] = red;
				components[1] = green;
				components[2] = blue;

				if (++x >= width) {
					x = 0;
					if (++y >= height) {
						y = 0;
						offsetX += width;
					}
				}
				if (offsetX == actualWidth) {
					if (--loops > 0) {						
						x = 0;
						y = 0;
						offsetX =0;
					} else {
						ended = true;
						return -1;
					}
				}

			}
			return components[cursor++];
		}
		return -1;
	}

}
